using System;
using Domain.Engine.Domain;
using SimpleCqrs.Commanding;
using SimpleCqrs.Domain;

namespace Domain.Engine.Commands
{
  public class CommandHandler :
    IHandleCommands<SayHelloCommand>,
    IHandleCommands<NewGameCommand>
  {
    private readonly IDomainRepository _repository;

    public CommandHandler(IDomainRepository repository)
    {
      _repository = repository;
    }

    public void Handle(ICommandHandlingContext<NewGameCommand> handlingContext)
    {
      if (_repository.GetById<GameAggregate>(Guid.Empty) != null)
      {
        handlingContext.Return(1);
        return;
      }

      var root = new GameAggregate(Guid.NewGuid());
      _repository.Save(root);
    }

    public void Handle(ICommandHandlingContext<SayHelloCommand> handlingContext)
    {
      if (_repository.GetById<HelloAggregate>(Guid.Empty) != null)
      {
        handlingContext.Return(1);
        return;
      }

      var root = new HelloAggregate(Guid.Empty, handlingContext.Command.Name);
      _repository.Save(root);
    }
  }
}